//
//  YSPNetworkTool.swift
//  Weibo Demo
//
//  Created by 朴裕识 on 15/12/19.
//  Copyright © 2015年 Apple. All rights reserved.
//

import UIKit
import AFNetworking

///使用枚举统一管理错误
enum YSPNetworkError: Int {
    case emptyAccessToken = -1 ///AccessToken没有值
    case emptyUID = -2 ///uid没有值
    
    //使用计算型属性，只有get方法
    var errorDescription: String {
        get {
            switch self {
                //根据不同的枚举值返回不同的错误信息
            case YSPNetworkError.emptyAccessToken:
                return "AccessToken没有值"
            case YSPNetworkError.emptyUID:
                return "uid没有值"
            }
        }
    }
    
    //定义一个方法,根据不同的枚举值返回不同的错误对象
    func error() -> NSError {
        return NSError(domain: "网络出错", code: self.rawValue, userInfo: ["errorDescription": errorDescription])
    }
    
}

class YSPNetworkTool: AFHTTPSessionManager {
    //设置单例
//    static let sharedNetworkTool: YSPNetworkTool = {
//        //https://api.weibo.com/2/statuses/public_timeline.json
//        //https://api.weibo.com/2/statuses/friends_timeline.json
//        //随便点几个接口的url发现都有相同的部分
//        let baseURL = NSURL(string: "https://api.weibo.com/")
//        let tool = YSPNetworkTool(baseURL: baseURL)
//        return tool
//    }()
    
    //这里设置单例的第二种方法
    //直接这一行代码就是单例了
    static let sharedNetworkTool = YSPNetworkTool()
    //重写默认的构造方法，修改序列化器，让它支持text/plain
    private init() {
        //super.init(baseURL: baseURL)是父类的便利构造函数
        //在构造函数里子类不能调用父类的便利构造函数
        //所以只能用下面这个
        let baseURL = NSURL(string: "https://api.weibo.com/")!
        super.init(baseURL: baseURL, sessionConfiguration: nil)
        
        //修改序列化器
        responseSerializer.acceptableContentTypes?.insert("text/plain")
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //MARK: - 授权相关
    let client_id = "1134649479"
    let redirect_uri = "http://www.baidu.com/"
    let client_secret = "250f6d62d8f8538b8648ef4c1ce1031b"
    
    //创建方法，返回请求Oauth授权时需要的URL
    func getOauthURL() -> NSURL {
        let OauthURLString = "https://api.weibo.com/oauth2/authorize?client_id=\(client_id)&redirect_uri=\(redirect_uri)"
        return NSURL(string: OauthURLString)!
    }
    
    //获取AccessToken
    func getAccessToken(code: String, finished: (response: [String: AnyObject]?, error: NSError?) -> ()) {
        let URLString = "https://api.weibo.com/oauth2/access_token"
        //封装请求参数的字典
        
        //        client_id	true	string	申请应用时分配的AppKey。
        //        client_secret	true	string	申请应用时分配的AppSecret。
        //        grant_type	true	string	请求的类型，填写authorization_code
        //
        //        grant_type为authorization_code时
        //        必选	类型及范围	说明
        //        code	true	string	调用authorize获得的code值。
        //        redirect_uri
        let param = [
            "client_id" : client_id,
            "client_secret" : client_secret,
            "grant_type" : "authorization_code",
            "code" : code,
            "redirect_uri" : redirect_uri
        ]
        
        //发送POST请求
        POST(URLString, parameters: param, success: { (_, response) -> Void in
            //成功的回调
        
            let dictionary = response as? [String: AnyObject]
            
            finished(response: dictionary, error: nil)
            
            }) { (_, error) -> Void in
                //失败的回调
                //调试时就算成功了也会报错误unacceptable content-type: text/plain"
                //原因是AFN默认的序列化器不支持content-type，在单例初始化的时候可以修改
        }
    }
    
    //MARK: - 加载数据
    func loadUserInfo(finished: (result: [String: AnyObject]?, error: NSError?) -> ()) {
        
        guard let access_token = YSPUserAccount.loadUserAccount()?.access_token else {
            let error = YSPNetworkError.emptyAccessToken.error()
            finished(result: nil, error: error)
            return
        }
        //能到这里说明accessToken有值
        guard let uid = YSPUserAccount.loadUserAccount()?.uid else {
            let error = YSPNetworkError.emptyUID.error()
            finished(result: nil, error: error)
            return
        }
        //能到这里说明有uid
        
        //url地址可以省略前面的baseURL，afn自动补齐的
        let URLString = "2/users/show.json"
        
        let params = [
            "access_token": access_token,
            "uid": uid
        ]
        
        GET(URLString, parameters: params, success: { (_, response) -> Void in
            //成功回调
            let dict = response as? [String: AnyObject]
            finished(result: dict, error: nil)
            }) { (_, error) -> Void in
                //失败回调
                finished(result: nil, error: error)
        }
    }
    
    func loadStatus(since_id: Int, max_id: Int, finished: (result: [String: AnyObject]?, error: NSError?) -> ()) {
        //URL:https://api.weibo.com/2/statuses/home_timeline.json
        //1.检查有没有accessToken
        guard let access_token = YSPUserAccount.userAccount?.access_token else {
            //来到这里说明没有accesstoken
            //返回错误给调用者
            finished(result: nil, error: YSPNetworkError.emptyAccessToken.error())
            return
        }
        //2.url地址
        let URLString = "https://api.weibo.com/2/statuses/home_timeline.json"
        //3.请求参数
        var parameters: [String: AnyObject] = ["access_token": access_token]
        if since_id > 0 {
            parameters["since_id"] = since_id
        }
        else if max_id > 0 {
            parameters["max_id"] = max_id
        }
        //4.发送请求
        GET(URLString, parameters: parameters, success: { (_, response) -> Void in
            //成功回调
            let dict = response as? [String: AnyObject]
            finished(result: dict, error: nil)
            }) { (_, error) -> Void in
                //失败回调
                finished(result: nil, error: error)
        }
    }
    
    
    
    
    
    
    
    
    
    
    
    
    
}
